//
//  CommentFormViewController.swift
//  iModern
//
//  Created by 立雄 王 on 15/6/29.
//  Copyright (c) 2015年 com.starlooking. All rights reserved.
//

import UIKit
import XLForm

class CommentFormViewController: FormViewController
{

    var articleId      = NSString()
    var commentManager = CommentManager()

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.initBackButton()

        let image  = UIImage(named: "Save-Small.png")
        let button = UIBarButtonItem(image: image?.imageWithRenderingMode(.AlwaysOriginal), style: .Plain, target: self, action: "addComment:")
        self.navigationItem.rightBarButtonItem = button

        self.initializeForm()

        // Do any additional setup after loading the view.
    }

    func initializeForm()
    {
        var form:    XLFormDescriptor
        var section: XLFormSectionDescriptor
        var row:     XLFormRowDescriptor

        form = XLFormDescriptor(title: "")
        section = XLFormSectionDescriptor.formSectionWithTitle("")
        section.footerTitle = ""
        form.addFormSection(section)

        row = XLFormRowDescriptor(tag: "message", rowType: XLFormRowDescriptorTypeTextView, title: "评论:")
        row.required = true
        section.addFormRow(row)

        self.form = form
    }

    func addComment(sender: AnyObject)
    {
        var message = self.formValues()["message"] as? NSString

        if message == nil
        {
            self.alertWarningMessage("请填写评价内容")
            return
        }

        if (message?.lengthOfBytesUsingEncoding(NSStringEncoding()) > 199)
        {
            message = message?.substringToIndex(199)
        }

        let rs = commentManager.addComment(self.articleId as String, comment: message as! String)
        if rs == nil
        {
            self.alertNetworkConnectionException()
            return
        }

        if rs!.hasErrors()
        {
            if rs?.errorCode == 3020
            {
                self.alertUserStatusException()
            }
            else
            {
                self.alertErrorMessage(rs!.errorMessage)
            }
        }
        self.view .endEditing(true)
        self.navigationController?.popViewControllerAnimated(true)
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
    }
    */

}
